package io.sage.controller;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import io.sage.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import io.sage.annotation.Login;
import io.sage.common.utils.R;
import io.sage.common.validator.ValidatorUtils;
import io.sage.entity.TokenEntity;
import io.sage.form.LoginFormVo;
import io.sage.modules.employer.entity.Employer;
import io.sage.modules.employer.service.EmployerService;
import io.sage.modules.weixin.LoginInfo;
import io.sage.resolver.MyHttpSessionListener;
import io.sage.service.TokenService;
import io.sage.util.ApiUserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 登录接口
 *
 */
@RestController
@RequestMapping("/sys")
@Api(tags="登录接口")
public class ApiLoginController {
	
	private static Logger logger = LoggerFactory.getLogger(ApiLoginController.class);
    @Autowired
    private TokenService tokenService;
    
    @Autowired
    private EmployerService studentService;

    @Autowired
    private UserService userService;

	
    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("login")
    @ApiOperation("登录登录名可以是：idcards  phone  username都可以登录")
    public R loginn(@RequestBody LoginFormVo form, HttpSession  session,HttpServletRequest request){
        //表单校验
        ValidatorUtils.validateEntity(form);
        /*if(io.sage.common.utils.StringUtils.isNotEmpty(form.getCode())){
            //获取openid
            String requestUrl = ApiUserUtils.getWebAccess(form.getCode());//通过自定义工具类组合出小程序需要的登录凭证 code
            logger.info("》》》组合token为：" + requestUrl);
            String res = restTemplate.getForObject(requestUrl, String.class);
            logger.info("res=="+res);
            JSONObject sessionData = JSON.parseObject(res);
            String openid=sessionData.getString("openid");
            String session_key=sessionData.getString("session_key");//不知道啥用。
            form.setOpenid(openid);
            form.setSessionKey(session_key);
            if(org.apache.commons.lang.StringUtils.isEmpty(form.getLatitude())){
                String ip= IPUtils.getIpAddr(request);
                form.setLatitude("ip");
                form.setLongitude(ip);
            }
        }*/
        Map<String, Object> map=new HashMap<>();
        //用户登录 普通用户
        if("0".equals(form.getSystem())){
           map = studentService.login(form);
        }else{
            map = userService.login(form);
        }

//        if(map.get("code")=="0"){
//        	session.setAttribute("loginName",map.get("userId"));
//        	logger.info("用户【"+map.get("userId")+"】登陆成功！");
//        }

        return R.ok(map);
    }
    
    /**
     * 使用微信登录
     * @param loginInfo
     * @return
     */
    @ApiOperation(value = "微信登录")
    @PostMapping("loginByWeixin")
    public R loginByWeixin(@RequestBody LoginInfo loginInfo) {
        //获取openid
        String requestUrl = ApiUserUtils.getWebAccess(loginInfo.getCode());//通过自定义工具类组合出小程序需要的登录凭证 code
        logger.info("》》》组合token为：" + requestUrl);
        String res = restTemplate.getForObject(requestUrl, String.class);
        logger.info("res=="+res);
        JSONObject sessionData = JSON.parseObject(res);
        String openid=sessionData.getString("openid");
        String session_key=sessionData.getString("session_key");//不知道啥用。
        if (null == sessionData || StringUtils.isEmpty(openid)) {
            return R.error("登录失败");
        }
        Map<String, Object> resultObj = new HashMap<String, Object>();
        resultObj.put("openid", openid);
        resultObj.put("sessionKey", session_key);
        return R.ok(resultObj);
    }
    /**
     *查询在线人数
     *
     */
    @PostMapping("/online")
    @ApiOperation("查询本系统当前在线人数")
    public R online() {
    	
    	int online = MyHttpSessionListener.online;
    	
        return  R.ok().put("online", online);
    }
    
    @PostMapping("forgetPassword")
    @ApiOperation("忘记密码")
    public R forgetPassword(HttpServletRequest request,@RequestBody JSONObject jsonObject){
    	
    	String phone = jsonObject.getString("phone");
    	
    	Employer student = studentService.selectByPhone(phone);
    	
    	if(student==null){
    		return R.error("手机号没有注册");
    	}
    	
    	String checkCode = jsonObject.getString("checkCode");
    	
    	//校验参数.
	  	if(StringUtils.isEmpty(checkCode)|| checkCode == null){
	  				
	  		return R.error("checkCode不能为空");
	  		
	  	 }
    	
    	String randomCode = (String) request.getSession().getAttribute("randomCode");
		
		if(randomCode==null||!randomCode.equals(checkCode)){
            //短信验证码错误
            return R.error("验证码错误");
        }
    	
    	return R.ok("验证正确");
    }
    
    @PostMapping("updatePwd")
    @ApiOperation("修改密码")
    public R updataPwd(@RequestBody JSONObject jsonObject){
    	
    	String password = jsonObject.getString("password");
    	
    	String confirmPassword = jsonObject.getString("newPassword");
    	
    	String phone = jsonObject.getString("phone");
    	
    	//校验参数.
  	    if(StringUtils.isEmpty(password)|| password == null){
  				
  		   return R.error("密码不能为空");
  	    }
  	    if(StringUtils.isEmpty(confirmPassword)|| confirmPassword == null){
  	    	
  	    	return R.error("密码确认不能为空");
  	    }
  	    
  	    Employer student = studentService.selectByPhone(phone);
  	    
  	    if(student!=null){
  	    	
  	    	student.setUserPwd(DigestUtils.sha256Hex(password));
  	    	
  	    }
  	    
  	    		
		int update = studentService.updateByPrimaryKeySelective(student);//全部更新
		
		if(update>0){
			
			return R.ok();
			
		}
		
		return R.error();
    }
    

    @Login
    @PostMapping("logout")
    @ApiOperation("退出")
    public R logout(@RequestBody JSONObject jsonObject,HttpServletRequest request){
    	
    	Integer userId = jsonObject.getInteger("userId");
    	
    	//校验参数.
  	    if(StringUtils.isEmpty(userId)|| userId == null){
  				
  		   return R.error("员工信息不能为空");
  	    }
  	    
  	    HttpSession session = request.getSession(false);//防止创建Session
  	    
	  	 if(session != null){
	          session.removeAttribute("loginName");
	          session.invalidate();
	     }
	     logger.info("用户退出登录结束！");
    	
        tokenService.expireToken(userId);
        
        return R.ok();
    }
    
    /**
     * 校验token。如果正确，返回新的token.
     * @param jsonObject
     * @return
     */
    @PostMapping("checkToken")
    @ApiOperation("校验token")
    public R checkToken(@RequestBody JSONObject jsonObject){
    	String token = jsonObject.getString("token");
    	TokenEntity tokenEntity = tokenService.queryByToken(token);
    	if(tokenEntity!=null){
    		TokenEntity createToken = tokenService.createToken(tokenEntity.getUserId());
    		return R.ok().put("msg", "token正确").put("token", createToken.getToken());
    	}else{
    		return R.error("token不对");
    	}
    }

}
